/*
 * @Date         : 2024-05-21 00:05:13 星期2
 * @Author       : xut
 * @Description  :
 */
import grpc from "@grpc/grpc-js"
export function authenticateInterceptor(
  methodDescriptor: any,
  call: grpc.ServerInterceptingCallInterface
) {
  const listener = new grpc.ServerListenerBuilder()
    .withOnReceiveMetadata((metadata, next) => {
      const path = methodDescriptor.path
      console.log("🚀 ~ listener ~ methodDescriptor.path:", path)

      // 如果是 auth 服务的路径，则不需要校验

      if (metadata.get("user")) {
        next(metadata)
      } else {
        call.sendStatus({
          code: grpc.status.UNAUTHENTICATED,
          details: "There is no user information in the metadata",
        })
      }
    })
    .build()

  const responder = new grpc.ResponderBuilder()
    .withStart((next) => next(listener))
    .build()

  return new grpc.ServerInterceptingCall(call, responder)
}
